/*
 * Copyright 2012-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xy.core.annotation;

import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.type.AnnotatedTypeMetadata;

/**
 * A Condition that evaluates a SpEL expression.
 *
 * @author Dave Syer
 * @author Stephane Nicoll
 * @see ConditionalOnExpression
 */
@Order(Ordered.LOWEST_PRECEDENCE - 20)
class OnConditionalEtl extends SpringBootCondition {

    @Override
    public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {

        String key = (String) metadata.getAnnotationAttributes(ConditionalOnEtl.class.getName()).get("key");
        String value = (String) metadata.getAnnotationAttributes(ConditionalOnEtl.class.getName()).get("value");
        ConditionMessage.Builder messageBuilder = ConditionMessage.forCondition(ConditionalOnEtl.class, "(" + key + ".contain[" + value + "])");
        if (key == null || key.length() == 0) {
            return new ConditionOutcome(false, messageBuilder.resultedIn(false));
        }
        if (value == null || value.length() == 0) {
            return new ConditionOutcome(false, messageBuilder.resultedIn(false));
        }
        String configServer = context.getEnvironment().getProperty(key);
        if (configServer == null || configServer.length() == 0) {
            return new ConditionOutcome(false, messageBuilder.resultedIn(false));
        }

        boolean result = false;
        String[] serverNames = configServer.split(",");
        for (String serverName : serverNames) {
            if (value.equalsIgnoreCase(serverName.trim())) {
                result = true;
            }
        }
        return new ConditionOutcome(result, messageBuilder.resultedIn(result));
    }


}
